/**
 * 
 */
package com.ihome.framework.core.event.command.lua;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.ihome.framework.core.cache.redis.IHomeRedisClient;


/**
 * @author zww
 *
 */
@Component
public class LuaCommandUploadProcessor implements InitializingBean{

    public static final Map<String, String> LUA_SHA_HASH = new HashMap<String, String>();

    @Autowired(required=false)
    private LuaCommandDto[] commandDtos;

    @Resource
    private IHomeRedisClient redisClient;



    public abstract static class LuaCommandDto{

        @Resource
        protected IHomeRedisClient redisClient;


        public  String name(){
            return getClass().getSimpleName();
        }
        public abstract String toLuaScript();

        public <T> T execute(String[] keys,String... args) throws Exception{
            return (T)redisClient.evalsha(getShaCode(), Arrays.asList(keys), Arrays.asList(args));
        }

        public String getShaCode(){
            return LUA_SHA_HASH.get(name());
        }
    }

    /* (non-Javadoc)
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        if(commandDtos != null){
            for (LuaCommandDto luaCommandDto : commandDtos) {
                redisClient.scriptFlush(luaCommandDto.name());
                String sha = redisClient.scriptLoad(luaCommandDto.toLuaScript(),luaCommandDto.name());
                Assert.hasText(luaCommandDto.name(), "not empty name...");
                Assert.isTrue(!LUA_SHA_HASH.containsKey(luaCommandDto.name()),"duplicate lua name...");
                LUA_SHA_HASH.put(luaCommandDto.name(), sha);
            }
        }
    }


}
